const {DEFAULT_PICTURE, REG_FOR_AT_WHO} = require('../conf/constant')
const {timeFormat} = require('../utils/dt')

const _formatUserPicture = (obj) => {
  if (!obj.picture) {
    obj.picture = DEFAULT_PICTURE
  }

  return obj
}

const formatUser = (list) => {
  if (list == null) {
    return list
  }

  if (list instanceof Array) {
    // 数组 用户列表
    return list.map(_formatUserPicture)
  }

  // 单个对象
  return _formatUserPicture(list)
}

const _formatDBTime = (obj) => {
  obj.createdAtFormat = timeFormat(obj.createdAt)
  obj.updatedAtFormat = timeFormat(obj.updatedAt)
  return obj
}

const _formatContent = (obj) => {
  obj.contentFormat = obj.content

  obj.contentFormat = obj.contentFormat.replace(
    REG_FOR_AT_WHO,
    (matchStr, nickName, userName) => {
      return `<a href="/profile/${userName}">@${nickName}</a>`
    }
  )

  return obj
}

const formatBlog = (list) => {
  if (list == null) {
    return list
  }

  if (list instanceof Array) {
    return list.map(_formatDBTime).map(_formatContent)
  }

  let result = list
  result = _formatDBTime(result)
  result = _formatContent(result)
  return result
}

module.exports = {
  formatUser,
  formatBlog
}
